package com.efounder.chat.item;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.app.ActivityOptionsCompat;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.MultiTransformation;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.efounder.chat.R;
import com.efounder.chat.activity.ViewPagerActivity;
import com.efounder.chat.item.manager.IMessageItem;
import com.efounder.chat.struct.MessageChildTypeConstant;
import com.efounder.chat.view.SendImgProgressView;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.ViewSize;
import com.efounder.frame.utils.Constants;
import com.efounder.message.struct.IMStruct002;
import com.efounder.util.JSONUtil;
import com.google.gson.JsonPrimitive;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import jp.wasabeef.glide.transformations.RoundedCornersTransformation;

/**
 * @author yqs 图片
 */
public class ImageMessageItem extends LinearLayout implements IMessageItem, View.OnClickListener {
    private Context mContext;
    private ImageView imageMessageView;
    private ProgressBar imageProgressBar;
    private TextView percentView;// 显示百分比的textview
    private TextView wifiCoverView;
    private LinearLayout messageItemLayout;
    private SendImgProgressView progressView;//显示发送进度
    private boolean isInUse;
    //数据M
    private IMStruct002 iMStruct002;
    private String path;// 图片路径
    private List<IMStruct002> datas;
    private List<IMStruct002> imageDatas = new ArrayList<>();
    private String[] urls;
    private int width, height;//图片宽高
    private MultiTransformation multi;

    public ImageMessageItem(Context context, List<IMStruct002> datas) {
        super(context);
        this.datas = datas;
        mContext = context;
        multi = new MultiTransformation(
                new CenterCrop(),
                new RoundedCornersTransformation(10, 0,
                        RoundedCornersTransformation.CornerType.ALL));

        initView(context);
    }

    private void initView(Context context) {
        LayoutInflater inflate = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        messageItemLayout = (LinearLayout) inflate.inflate(R.layout.chat_item_message_image, this);
        LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        this.setLayoutParams(lp);
        imageMessageView = (ImageView) messageItemLayout
                .findViewById(R.id.iv_sendPicture);
        imageProgressBar = (ProgressBar) messageItemLayout
                .findViewById(R.id.progressBar);
        percentView = (TextView) messageItemLayout
                .findViewById(R.id.percentage);
        progressView = (SendImgProgressView) messageItemLayout.findViewById(R.id.progressView);
        wifiCoverView = (TextView) messageItemLayout.findViewById(R.id.tv_wifi);
        wifiCoverView.setOnClickListener(this);

        //设置监听
        this.setOnClickListener(this);
    }

    @Override
    public void setIMStruct002(IMStruct002 message) {

        this.iMStruct002 = message;
        try {
            dataChanged(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void dataChanged(IMStruct002 iMStruct002) {
        //1.根据数据显示view
        setUpImageViewParams(iMStruct002);
        if (!iMStruct002.getMessage().contains("url")) {//判断是否是JSON数据,没有"url"的话为以前的消息结构
            path = iMStruct002.getMessage().trim();
            showRevImg();
        } else {
            //判断是否是发送的图片,如果是,则加载本地图片路径
            if (iMStruct002.getFromUserId() == Integer.valueOf(EnvironmentVariable.getProperty(Constants.CHAT_USER_ID))) {
                wifiCoverView.setVisibility(View.GONE);
                path = JSONUtil.parseJson(iMStruct002.getMessage()).get("path").getAsString();
                if (!new File(path).exists()) {
                    path = JSONUtil.parseJson(iMStruct002.getMessage()).get("url").getAsString();
                    progressView.setVisibility(View.GONE);
                    showRevImg();
                    return;
                }
                path = "file://" + path;
                //之前版本IMStruct无progress,则使用以前的方法加载
                if (iMStruct002.getExtra("progress") == null) {
                    showRevImg();
                } else {
                    imageProgressBar.setVisibility(View.GONE);
                    percentView.setVisibility(View.GONE);
                    Glide.with(mContext).load(path)
                            .apply(new RequestOptions()
//                            .placeholder(R.drawable.loading_image_background)
                                    .error(R.drawable.loading_image_background)
//                                    .transform(new RoundedCorners(10))
                                    .transform(multi)


                                    .diskCacheStrategy(DiskCacheStrategy.ALL))
                            .into(imageMessageView);

                    Object object = iMStruct002.getExtra("progress");
                    if ((object instanceof JsonPrimitive && ((JsonPrimitive) object)
                            .getAsInt() == -1) || (object instanceof Integer && (int) object == -1)) {
                        //progress为-1，说明发送失败，隐藏进度条
                        progressView.setVisibility(View.GONE);
                    } else {
                        //本地预发送图片的view
                        progressView.setVisibility(View.VISIBLE);
                        int progress = 0;
                        if ((object instanceof JsonPrimitive)) {
                            progress = ((JsonPrimitive) object).getAsInt();
                        } else {
                            progress = (int) object;
                        }
                        progressView.setProgress(progress);
                        if (progress == 100) {
                            progressView.setVisibility(View.GONE);
                        }
                    }
                }

            } else {
                path = JSONUtil.parseJson(iMStruct002.getMessage()).get("url").getAsString();
                if (!isWifiConnected(mContext)) {
                    imageProgressBar.setVisibility(View.GONE);
                    Glide.with((Activity) mContext)
                            .load(path)
                            .apply(new RequestOptions()
                                            .onlyRetrieveFromCache(true)//非wifi下默认从缓存读取
                                            .diskCacheStrategy(DiskCacheStrategy.ALL)
                                            //.transform(new RoundedCorners(10))
                                            .transform(multi)
                                    // .skipMemoryCache(true)
                            )

                            .listener(new RequestListener<Drawable>() {
                                //无缓存时加载覆盖图，点击下载图片
                                @Override
                                public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                                    wifiCoverView.setVisibility(View.VISIBLE);
                                    return false;
                                }

                                @Override
                                public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                                    wifiCoverView.setVisibility(View.GONE);
                                    return false;
                                }
                            })
                            .into(imageMessageView);


                } else {
                    progressView.setVisibility(View.GONE);
                    showRevImg();
                }
            }
        }
    }

    /**
     * 通过图片的宽高比例确定imageview大小
     *
     * @param iMStruct002
     */
    public void setUpImageViewParams(IMStruct002 iMStruct002) {
        String scale = JSONUtil.parseJson(iMStruct002.getMessage()).get("scale").getAsString();
        width = Integer.valueOf(scale.substring(0, scale.indexOf(":")));
        height = Integer.valueOf(scale.substring(scale.indexOf(":") + 1, scale.length()));
        Log.i("ImageMessageItem: ", "width=" + width + " height=" + height);
        int reSizeWidth = 0;
        int reSizeHeight = 0;

        //图片宽大于100dp 并且图片高度大于宽度 ，设置宽度100dp 高度重新计算(竖图)
        if ((width > dp2px(100)) && (height > width)) {
            reSizeWidth = dp2px(100);
            reSizeHeight = (int) (height * ((float) reSizeWidth / (float) width));

        } else if ((width > dp2px(150)) && (width >= height)) {
            //图片宽大于150dp 并且图片宽度大于 高度，设置宽度150dp 高度重新计算(横图)
            reSizeWidth = dp2px(150);
            reSizeHeight = (int) (height * ((float) reSizeWidth / (float) width));
        } else if (width < dp2px(80)) {
            //图片宽小于80dp 设置宽度 80 高度计算
            reSizeWidth = dp2px(80);
            reSizeHeight = (int) (height * ((float) reSizeWidth / (float) width));
        } else {
            reSizeHeight = height;
            reSizeWidth = width;
        }
        if (reSizeHeight != 0) {
            if (reSizeHeight > 1500) reSizeHeight = 1500;
            this.getLayoutParams().height = reSizeHeight;
            this.getLayoutParams().width = reSizeWidth;
            imageMessageView.getLayoutParams().height = reSizeHeight;
            imageMessageView.getLayoutParams().width = reSizeWidth;
            wifiCoverView.getLayoutParams().height = reSizeHeight;
            wifiCoverView.getLayoutParams().width = reSizeWidth;
        }
        Log.i("ImageMessageItem: ", "reSizeWidth=" + reSizeWidth + " reSizeHeight=" + reSizeHeight);

    }

    @Override
    public void onClick(View v) {
//        if (v.getId() == R.id.iv_sendPicture) {
//        }
        if (v.getId() == R.id.tv_wifi) {
            wifiCoverView.setVisibility(View.GONE);
            showRevImg();
        } else {
            //跳转共享元素动画
            Intent intent = new Intent(mContext, ViewPagerActivity.class);
            intent.putExtra("urls", urls);
            int position = imageDatas.indexOf(iMStruct002);
            intent.putExtra("position", position);

            ActivityOptionsCompat options = ActivityOptionsCompat
                    .makeSceneTransitionAnimation((Activity) mContext, imageMessageView, "imageItem");

            ActivityCompat.startActivity(mContext, intent, options.toBundle());

        }
    }

    private void showRevImg() {
        imageProgressBar.setVisibility(View.VISIBLE);
        Glide.with((Activity) mContext).load(path)
                .apply(new RequestOptions()
                                .error(R.drawable.loading_image_background)
                                .diskCacheStrategy(DiskCacheStrategy.ALL)
                                //.transform(new RoundedCorners(10))
                                .transform(multi)
                        // .skipMemoryCache(true)
                )
                .listener(new RequestListener<Drawable>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                        imageProgressBar.setVisibility(View.GONE);
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                        imageProgressBar.setVisibility(View.GONE);
                        return false;
                    }
                }).into(imageMessageView);

    }


    @Override
    public View messageView() {
        return this;
    }

    @Override
    public ViewSize messageViewSize() {
        return null;
    }

    @Override
    public boolean getIsInUse() {
        return this.isShown();
    }

    @Override
    public void setIsInUse(boolean isInUse) {
        this.isInUse = isInUse;
    }

    @Override
    public void prepareForReuse() {
        progressView.setVisibility(View.GONE);
        // imageMessageView.setImageResource(R.drawable.loading_image_background);
    }

    private int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                getResources().getDisplayMetrics());
    }

    /**
     * 判断WiFi是否可用
     *
     * @param context
     * @return true wifi已连接  false wifi未连接
     */
    public boolean isWifiConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mWiFiNetworkInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            if (mWiFiNetworkInfo != null) {
                if (mWiFiNetworkInfo.isConnected()) {
                    return true;
                }
                return false;
            }
        }
        return false;
    }

    public void setMessageList(List<IMStruct002> list) {
        this.datas = list;
        if (this.datas == null) {
            this.datas = new ArrayList<>();
        }
        imageDatas.clear();
        List<String> datas2 = new ArrayList<>();
        int count = 0;
        //筛选出list<IMStruct002>中的图片路径
        for (int i = 0; i < datas.size(); i++) {
            String url = null;
            if (datas.get(i).getMessageChildType() == MessageChildTypeConstant.subtype_image) {
                IMStruct002 imageIMStruct002 = datas.get(i);
                if (!datas.get(i).getMessage().contains("url")) {//判断是否是JSON数据,没有"url"的话为以前的消息结构
                    url = datas.get(i).getMessage().trim();
                } else {//否则为JOSN消息结构
                    try {
                        if (datas.get(i).getFromUserId() == Integer.valueOf(EnvironmentVariable.getProperty(Constants.CHAT_USER_ID))) {
                            //本地路径
                            url = JSONUtil.parseJson(datas.get(i).getMessage()).get("path").getAsString();
                            if (!new File(url).exists()) {
                                //本地不存在则网络地址
                                url = JSONUtil.parseJson(datas.get(i).getMessage()).get("url").getAsString();
                            } else {
                                url = "file://" + url;
                            }
                        } else {
                            //接收的图片用网络地址
                            url = JSONUtil.parseJson(datas.get(i).getMessage()).get("url").getAsString();
                        }
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }
                }
                datas2.add(count, url);
                count++;
                imageDatas.add(imageIMStruct002);
            }
        }
        urls = new String[datas2.size()];
        for (int i = 0; i < datas2.size(); i++) {
            urls[i] = datas2.get(i);
        }
    }
}